var colors = require('../utils/colors.js');
const app = getApp();

Page({
  data: {
    weekArray: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周', '第7周', '第8周', '第9周', '第10周', '第11周', '第12周', '第13周', '第14周', '第15周', '第16周', '第17周', '第18周', '第19周', '第20周'],
    pageNum: 0, // 当前所在分类的索引
    todayDay: '', // 今日日期
    todayMonth: '', // 今日月份
    todayWeek: '', // 今日周
    day: '', // 日期
    month: '', // 月份
    monthNum: 1,
    week: ['日', '一', '二', '三', '四', '五', '六'],
    nowDay: [1, 2, 3, 4, 5, 6, 7], // 本周的七天日期
    schoolTime: ['2024', '08', '26'], // 本学期开学时间
    nowWeek: '', // 当前周
    course_time: [
      ['8:15', '9:00'],
      ['9:05', '9:50'],
      ['10:05', '10:50'],
      ['10:55', '11:40'],
      ['14:30', '15:15'],
      ['15:20', '16:05'],
      ['16:20', '17:05'],
      ['17:10', '17:55'],
      ['19:10', '19:55'],
      ['20:00', '20:45'],
      ['20:50', '21:35']
    ],
    wList: [], // 从服务器获取课程数据
    colorArrays: colors, // 模块化课表颜色数组，顶部导入
    showAddModal: false, // 是否显示添加课程模态框
    newCourse: { // 新课程的初始数据
      name: '',
      address: '',
      jie: 1,
      classNumber: 1, 
      isToday: 1, 
      week: 1, 
      id: 1 
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let nowWeek = this.getNowWeek();
    let nowDay = this.getDayOfWeek(nowWeek);
    let pageNum = nowWeek - 1;
    let month = this.getMonth((nowWeek - 1) * 7);
    this.setData({
      nowWeek,
      nowDay,
      pageNum,
      todayWeek: nowWeek,
      monthNum: month / 1, // 当前月份数字类型，用于数字运算
      colorArrays: colors // 课表颜色
    });

    // 获取课程数据
    this.getCourseList(nowWeek);
  },

  // 获取第几周后的月份
  getMonth(days) {
    let [year, month, day] = this.data.schoolTime;
    var date = new Date(year, month - 1, day);
    date.setDate(date.getDate() + days); //获取n天后的日期      
    var m = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
    return m;
  },

  // 获取第几周后的星期几的日期
  getDay(days) {
    let [year, month, day] = this.data.schoolTime;
    var date = new Date(year, month - 1, day);
    date.setDate(date.getDate() + days); //获取n天后的日期      
    var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //获取当前几号，不足10补0    
    return d;
  },

  // 获取当前周
  getNowWeek() {
    var date = new Date();
    let [year, month, day] = this.data.schoolTime;
    var start = new Date(year, month - 1, day);
    //计算时间差
    var left_time = parseInt((date.getTime() - start.getTime()) / 1000) + 24 * 60 * 60;
    var days = parseInt(left_time / 3600 / 24);
    var week = Math.floor(days / 7) + 1;
    var result = week;
    if (week > 20 || week <= 0) {
      result = this.data.now_week;
    }
    return result;
  },

  //获取一周的日期
  getDayOfWeek(week) {
    var day = [];
    for (var i = -1; i < 6; i++) {
      var days = (week - 1) * 7 + i;
      day.push(this.getDay(days));
    }
    return day;
  },

  // 获取课表数据
// 获取课表数据
async getCourseList(week) {
  let that = this;
  wx.request({
    url: `http://localhost:3000/courses?week=${week}`,
    method: 'GET',
    success: (res) => {
      console.log('Response from server:', res); // 添加调试信息
      if (res.statusCode === 200) {
        // 确保返回的数据是一个数组
        if (Array.isArray(res.data)) {
          // 将数据设置到 wList 中
          that.setData({
            [`wList[${week-1}]`]: res.data // 直接设置对应周的课程数据
          });
          console.log('课程数据加载成功:', that.data.wList); // 调试输出
        } else {
          console.error('后端返回的数据格式不正确，应为数组');
        }
      } else {
        console.error('Failed to fetch course data:', res.data);
      }
    },
    fail: (err) => {
      console.error('Request failed:', err);
    }
  });
},


  // 点击切换导航的回调
  changeNav(event) {
    let pageNum = event.currentTarget.dataset.page;
    let nowWeek = pageNum + 1;
    let nowDay = this.getDayOfWeek(nowWeek);
    let month = this.getMonth((nowWeek - 1) * 7);
    this.setData({
      pageNum,
      nowWeek,
      nowDay,
      month,
      monthNum: month / 1, // 当前月份数字类型，用于数字运算
    });

    // 获取课程数据
    this.getCourseList(nowWeek);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      todayDay: new Date().getDate(),
      todayMonth: new Date().getMonth() + 1,
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
    });
  },
  add: function() {
    this.setData({
      showAddModal: true
    });
  },
    // 关闭模态框
    closeModal: function() {
      this.setData({
        showAddModal: false
      });
    },
  
    // 输入课程信息
    inputCourseName: function(e) {
      this.setData({
        [`newCourse.name`]: e.detail.value
      });
    },
    inputCourseAddress: function(e) {
      this.setData({
        [`newCourse.address`]: e.detail.value
      });
    },
    inputCourseJie: function(e) {
      this.setData({
        [`newCourse.jie`]: e.detail.value
      });
    },
    inputCourseClassNumber: function(e) {
      this.setData({
        [`newCourse.classNumber`]: e.detail.value
      });
    },
    inputCourseIsToday: function(e) {
      this.setData({
        [`newCourse.isToday`]: e.detail.value
      });
    },
    inputCourseWeek: function(e) {
      this.setData({
        [`newCourse.week`]: e.detail.value
      });
    },
    inputCourseId: function(e) {
      this.setData({
        [`newCourse.id`]: e.detail.value
      });
    },
  
    // 提交课程信息
    submitCourse: function() {
      let that = this;
      wx.request({
        url: `http://localhost:3000/courses`,
        method: 'POST',
        data: that.data.newCourse,
        success: (res) => {
          if (res.statusCode === 201) {
            console.log('课程添加成功:', res.data);
            that.getCourseList(that.data.nowWeek);
            that.closeModal();
          } else {
            console.error('添加课程失败:', res.data);
          }
        },
        fail: (err) => {
          console.error('Request failed:', err);
        }
      });
    }
});
